package cn.bankAutoOffice.service.impl;

import cn.bankAutoOffice.bean.entity.File;
import cn.bankAutoOffice.mapper.FileMapper;
import cn.bankAutoOffice.service.FileService;
import cn.bankAutoOffice.service.RedisService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 金健伟
 * @DATE 2023/4/12 11:21
 * 功能说明：
 */

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileMapper fileMapper;

    @Resource
    private RedisService redisService;

    @Override
    public Integer countFile(Integer fileType) {
        String count;
        if (fileType == null){
            count = redisService.getValue("allFileCount");
            if (count != null && !"".equals(count)){
                return Integer.parseInt(count);
            } else {
                Integer integer = fileMapper.countFile(fileType);
                redisService.putValue("allFileCount",integer);
                return integer;
            }
        } else {
            count = redisService.getValue("allFileCount" + fileType);
            if (count != null && !"".equals(count)){
                return Integer.parseInt(count);
            } else {
                Integer integer = fileMapper.countFile(fileType);
                redisService.putValue("allFileCount" + fileType,integer);
                return integer;
            }
        }

    }

    @Override
    public List<File> getFileAll(Integer fileType) {
        List<File> files;
        String value;
        if (fileType == null){
            value = redisService.getValue("fileAll");
            if (value != null && !"".equals(value)){
                files = JSONObject.parseArray(value);
            } else {
                files = fileMapper.getFileAll(fileType);
                redisService.putValue("fileAll",files,5);
            }
        } else {
            value = redisService.getValue("fileAll" + fileType);
            if (value != null && !"".equals(value)){
                files = JSONObject.parseArray(value);
            } else {
                files = fileMapper.getFileAll(fileType);
                redisService.putValue("fileAll" + fileType,files,5);
            }
        }

        return files;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public File getFile(String fileName) {
        return fileMapper.getFile(fileName);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer addFile(File File) {
        return fileMapper.addFile(File);
    }
}
